import * as ysApis from "@/apis/g.ys";
import { getCachedValue } from "@/utils/local-storage-cache";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const YS_NATIONS_KEY = "__ys_nations__";

type DYsNation = {
  chanId: string;
  key: string;
  infoId: number;
  name: string;
  ext: Record<string, string | { name: string; url: string }>;
};

const NATION_KEY_TO_CHAN_ID: { [nk: string]: string } = {
  mondstadt: "727",
  liyue: "728",
  inazuma: "729",
  sumeru: "730",
  fontaine: "731",
  natlan: "936",
};

const toDYsNation = (it: DYsContentItem): DYsNation => {
  const ext = JSON.parse(it.sExt);
  const key = ext["742_0"] as string;
  return {
    chanId: NATION_KEY_TO_CHAN_ID[key],
    infoId: it.iInfoId,
    name: it.sTitle,
    ext,
    key,
  };
};

export const useYsStore = defineStore("ys", () => {
  const router = useRouter();
  const route = useRoute();
  const nations = ref<DYsNation[]>([]);
  const nationsLoading = ref(false);
  const activeNationKey = ref<string>(
    (() => {
      const v = route.query.n ?? "";
      return typeof v === "string" ? v : (v[0] ?? "");
    })(),
  );
  const activeNation = computed(() => {
    return nations.value.filter((it) => it.key === activeNationKey.value)?.[0];
  });

  const activeNationChanId = computed(() => {
    return activeNation.value?.chanId;
  });

  const loadNations = async () => {
    nationsLoading.value = true;
    try {
      nations.value = await getCachedValue(YS_NATIONS_KEY, 3600 * 24 * 7, async () => {
        const resp = await ysApis.getNations();
        return resp.data.list.map(toDYsNation).filter((it) => it.key in NATION_KEY_TO_CHAN_ID);
      });
    } catch (e) {
      console.error("Error occurs when loading ys nations:", e);
    } finally {
      nationsLoading.value = false;
    }
  };

  const setActiveNationKey = (key: string) => {
    activeNationKey.value = key;
    router.replace({ query: { n: key } });
  };

  return {
    nations,
    nationsLoading,
    loadNations,
    activeNation,
    activeNationKey,
    activeNationChanId,
    setActiveNationKey,
  };
});
